/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sudoku;

//import java.awt.*;
import java.awt.Color;
import javax.swing.*;

/**
 *
 * @author Roy
 */
public class Link {

	private Square[] squares;
	private int length;

	public final int maxLength;

	public Link(int len) {
		length = 0;
		maxLength = len;
		squares = new Square[len];
	}

	public void add(Square sq) {
		squares[length] = sq;
		length++;
	}

	//true - if a square changed in the method
	public boolean scan() {
		boolean ret = false;

		numbers:
		for(int i = 1; i <= length; i++) {
			int m = 0;
			int count = 0;
			for(int j = 0; j < length; j++) {
				if(squares[j].get() == i) {
					continue numbers;
				}
				else if(squares[j].can(i)) {
					count++;
					m = j;
				}
			}
			if(count == 1) {
				squares[m].is(i);
				ret = true;
			}
		}
		return ret;
	}

	//true - if a square changed in the method
	public boolean update() {
		boolean ret = false;
		for(int i = 0; i < length; i++) {
			int num = squares[i].get();
			if(num != 0) {
				for(int j = 0; j < length; j++) {
					if(squares[j].get() != 0) {
                        try{
							squares[j].cant(num);
						}
						catch(RuntimeException e) {
							squares[i].setBackground(Color.RED);
							throw new RuntimeException();
						}
						ret = true;
                    }
				}
			}
		}
		return ret;
	}
}
